package com.lans.alg;

import java.util.Arrays;

/**
 * @author: lans
 * @date: 2025/3/11
 * @name: 刘宇
 */
public class KMP {
    public static void main(String[] args) {
        int[] next = kmpNext("abcabx");
        int i = kmpSearch("abcabcabx","abcabx",next);
        System.out.println(i);
    }

    public static int kmpSearch(String str1, String str2, int[] next) {
        for(int i=0,j=0;i<str1.length();i++){

            while(j>0&&str1.charAt(i)!=str2.charAt(j)){
                j = next[j-1];
            }

            if(str1.charAt(i)==str2.charAt(j)){
                j++;
            }
            if(j==str2.length()){
                return i-j+1;
            }
        }
        return -1;
    }

    /**
     *
     * @param desc 子串
     * @return 部分匹配值数组
     */
    public static int[] kmpNext(String desc){
        int[] arr = new int[desc.length()];
        arr[0]=0;
        for(int i=1,j=0;i<desc.length();i++){

            while(j>0&&desc.charAt(i)!=desc.charAt(j)){
                j = arr[j-1];
            }

            if(desc.charAt(i)==desc.charAt(j)){
                j++;
            }
            arr[i]=j;
        }
        return arr;
    }
}